import { Component, OnInit, Input, Output, EventEmitter, OnChanges, SimpleChanges } from '@angular/core';

@Component({
  selector: 'page',
  template: `
    <div class="cust-pagination">
      <span>当前显示 {{totalRecord==0?0:(currentPage-1)*showRecord+1}} 到 {{currentPage*showRecord>totalRecord?totalRecord:currentPage*showRecord}} 条，共 {{totalRecord}} 条记录。</span>
      <ul>
        <li class="prev" [ngClass]="{'disabled': currentPage==1}" (click)="queryData('prev')">上一页</li>
        <li *ngFor="let page of pages" [ngClass]="{'current': currentPage==page}"
          (click)="queryData(page)">{{page}}</li>
        <li class="next" [ngClass]="{'disabled': currentPage==totalPage}" (click)="queryData('next')">下一页</li>
      </ul>
    </div>
  `,
  styles:[`
    .cust-pagination {display: table; width: 100%; font-size: 14px;line-height: 34px; }
    .cust-pagination span {border: 1px solid white; float: left;}
    .cust-pagination ul {padding: 0; margin: 0; float: right;}
    .cust-pagination li {display: inline-block; width: 40px; text-align: center; cursor: pointer; background-color: #fff; border: 1px solid #ddd;margin-left: -1px; color: #337ab7; float: left;}
    .cust-pagination li:hover {background-color: #eee;}
    .cust-pagination li.prev, .cust-pagination li.next {width: 60px;}
    .cust-pagination li.current {color: #fff; background-color: #337ab7; border-color: #337ab7; cursor: auto;}
    .cust-pagination li.disabled {color: #777; cursor: auto;}
  `]
})

export class PageComponent implements OnInit, OnChanges {
  
  @Output() loadData = new EventEmitter();
  @Input() currentPage:number;
  @Input() showRecord:number;
  @Input() totalRecord:number;
  private totalPage:number;
  private pages: number[];
  
  constructor() { }
  
  ngOnInit() { }

  ngOnChanges(changes: SimpleChanges) {
    this.pages = [];
    if(this.totalRecord > 0) {
      this.totalPage = Math.ceil(this.totalRecord / this.showRecord);
      let startPage = this.currentPage-3<1 ? 1 : this.currentPage-3;
      let endPage = startPage+6>this.totalPage ? this.totalPage : startPage+6;
      startPage = endPage-6>0 ? endPage-6 : 1;
      for (let index = startPage; index <= endPage; index++) {
        this.pages.push(index);
      }
    } else {
      this.totalPage = 1;
    }
  }

  queryData(pageNumber) {
    if(pageNumber == 'prev') {
      pageNumber = this.currentPage-1<1 ? 1 : this.currentPage-1;
    } else if(pageNumber == 'next') {
      pageNumber = this.currentPage+1>this.totalPage ? this.totalPage : this.currentPage+1;
    }
    if(pageNumber != this.currentPage) {
      this.loadData.emit(pageNumber);
    }
  }
}
  